package com.hmall.service;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.hdmall.business.common.common.Const;
import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.BigDecimalUtil;
import com.hmall.mapper.MallCartMapper;
import com.hmall.mapper.MallPriceMapper;
import com.hmall.mapper.MallProductMapper;
import com.hmall.model.MallCart;
import com.hmall.model.MallProduct;
import com.hdmall.business.common.util.PropertiesUtil;
import com.hmall.vo.CartProductVo;
import com.hmall.vo.CartVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CartService {

    private final static int CHECK = 1;

    private final static int UN_CHECK = 0;

    @Autowired
    private MallCartMapper cartMapper;

    @Autowired
    private MallProductMapper productMapper;

    @Autowired
    private MallPriceMapper mallPriceMapper;



    public ServerResponse<CartVo> add(Integer userId, Integer productId, String grade, BigDecimal weight){
        if(productId == null || weight == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        //得到cart
        MallCart cart = cartMapper.selectCartByUserIdProductId(userId,productId,grade);
        if(cart == null){
            //这个产品不在这个购物车里,需要新增一个这个产品的记录
            MallCart cartItem = new MallCart();
            cartItem.setWeight(weight);
            cartItem.setChecked(Const.Cart.CHECKED);
            cartItem.setGrade(grade);
            cartItem.setProductId(productId);
            cartItem.setUserId(userId);
            //产品id查询商家id
            Integer shopId= null;
            try {
                shopId = productMapper.selectShopIdByProductId(productId);
            } catch (Exception e) {
                e.printStackTrace();
                return  ServerResponse.createByStatus(ResponseCode.SHOP_NOT_FOUND.getCode(),ResponseCode.SHOP_NOT_FOUND.getDesc(),null);
            }
            if (null==shopId){
                return  ServerResponse.createByStatus(ResponseCode.SHOP_NOT_FOUND.getCode(),ResponseCode.SHOP_NOT_FOUND.getDesc(),null);
            }
            cartItem.setShopId(shopId);
            cartMapper.insert(cartItem);
        }else{
            //这个产品已经在购物车里了.
            //如果产品已存在,数量相加
            weight = cart.getWeight().add(weight);
            cart.setWeight(weight);
            cartMapper.updateCartOnlyWeight(cart);
        }

        return this.list(userId);
    }

    public ServerResponse<CartVo> update(Integer userId, Integer cartId, BigDecimal weight){
        if(cartId == null || weight == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //根据productId获得当前产品的购物车属性
        MallCart cart = cartMapper.selectByPrimaryKey(cartId);

        if(cart != null){
            cart.setWeight(weight);
        }
        cartMapper.updateByPrimaryKey(cart);
        System.out.println(cart);
        return this.list(userId);
    }
    //根据用户id 等级 产品等 查询购物车id
    public ServerResponse selectCartIdByGrdWtPrUsr(Integer userId, Integer productId,  Integer weight,String grade){
        Integer cartId= 0;
        try {
            cartId = cartMapper.selectCartIdByGrdWtPrUsr(userId,productId,weight,grade);
        } catch (Exception e) {
            e.printStackTrace();
            ServerResponse.createByStatus(300,"根据用户id 等级产品等查询购物车id失败","");
        }
        if (null==cartId){
            ServerResponse.createByStatus(300,"购物车没有此产品","");
        }
        return  ServerResponse.createBySuccess(cartId);

    }
    public ServerResponse<CartVo> deleteProduct(Integer userId, String cartIds){
        List<String> cartIdList = Splitter.on(",").splitToList(cartIds);
        if(CollectionUtils.isEmpty(cartIdList)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        cartMapper.deleteByUserIdcartIds(userId,cartIdList);
        return this.list(userId);
    }
    //列出已经选中的产品列表
    public ServerResponse<CartVo> listCheck(Integer userId){
        CartVo cartVo = this.getCartVoLimit(userId, CHECK);
        return ServerResponse.createBySuccess(cartVo);
    }
    //列出所有购物车列表
    public ServerResponse<CartVo> list(Integer userId){

        CartVo cartVo = this.getCartVoLimit(userId, UN_CHECK);
        return ServerResponse.createBySuccess(cartVo);
    }

    public ServerResponse<CartVo> selectOrUnSelect (Integer userId, Integer cartId, Integer checked){
        cartMapper.checkedOrUncheckedProduct(userId,cartId,checked);
        return this.list(userId);
    }

    public ServerResponse<Integer> getCartProductCount(Integer userId){
        if(userId == null){
            return ServerResponse.createBySuccess(0);
        }
        return ServerResponse.createBySuccess(cartMapper.selectCartProductCount(userId));
    }

    private CartVo getCartVoLimit(Integer userId, Integer check){
        CartVo cartVo = new CartVo();
        List<MallCart> cartList = cartMapper.selectCartByUserId(userId);
        List<CartProductVo> cartProductVoList = Lists.newArrayList();
        BigDecimal cartTotalPrice = new BigDecimal("0");

        //如果购物车不为空
        if(CollectionUtils.isNotEmpty(cartList)){
            for(MallCart cartItem : cartList){

                MallProduct product = new MallProduct();
                //列出购物车里所有
                if(check == UN_CHECK) {
                    product = productMapper.selectByProductId(cartItem.getProductId());
                 }
                //列出购物车里勾选的
                else if(check == CHECK){
                    //如果是勾选的产品记录
                    if(cartItem.getChecked() == 1) {
                        product = productMapper.selectByProductId(cartItem.getProductId());
                    } else{
                    //如果不是勾选的直接跳过
                        continue;
                    }
                }

                if(product == null) {
                    continue;
                }

                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setGrade(cartItem.getGrade());
                cartProductVo.setId(cartItem.getId());
                cartProductVo.setUserId(userId);
                cartProductVo.setProductId(cartItem.getProductId());
                cartProductVo.setWeight(cartItem.getWeight());


                cartProductVo.setProductMainImage(product.getMainImage());
                cartProductVo.setProductName(product.getName());
                cartProductVo.setProductSubtitle(product.getSubtitle());
                cartProductVo.setProductStatus(product.getStatus());


                //阶梯状价格
                BigDecimal price = new BigDecimal(0);
                int productId = cartItem.getProductId();
                BigDecimal weight = cartProductVo.getWeight();
                String grade = cartItem.getGrade();
                System.out.println(productId + "+" + weight+ "+" + grade);
                price = mallPriceMapper.selectPriceNum(productId, weight, grade);

                System.out.println("price" + price);
                cartProductVo.setProductPrice(price);

                cartProductVo.setProductStock(product.getStock());
                //判断库存
                BigDecimal buyLimitCount = new BigDecimal(0.0);
                if(product.getStock() >= cartItem.getWeight().intValue()){
                    //库存充足的时候
                    buyLimitCount = cartItem.getWeight();
                    //cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                    cartProductVo.setLimitWeight(Const.Cart.LIMIT_NUM_SUCCESS);
                }else{
                    buyLimitCount = new BigDecimal(product.getStock());
                    cartProductVo.setLimitWeight(Const.Cart.LIMIT_NUM_FAIL);
                    //购物车中更新有效库存
                    MallCart cartForWeight = new MallCart();
                    cartForWeight.setId(cartItem.getId());
                    cartForWeight.setWeight(buyLimitCount);
                    //更新数据库的接口
                    cartMapper.updateByPrimaryKeySelective(cartForWeight);
                }
                cartProductVo.setWeight(buyLimitCount);
                //计算总价
                System.out.println(cartItem.getProductId() + "+" + buyLimitCount);

                //根据重量计算价格
                BigDecimal priceNum = mallPriceMapper.selectPriceNum(cartItem.getProductId(), buyLimitCount, cartItem.getGrade());
                // 如果没取到，使用产品列表价格
                if (priceNum == null) {
                    priceNum = product.getPrice();
                }

                System.out.println(priceNum);
                cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(priceNum.doubleValue(),cartProductVo.getWeight().doubleValue()));
                cartProductVo.setProductChecked(cartItem.getChecked());

                if(cartItem.getChecked() == Const.Cart.CHECKED){
                    //如果已经勾选,增加到整个的购物车总价中
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(),cartProductVo.getProductTotalPrice().doubleValue());
                }
                cartProductVoList.add(cartProductVo);
            }
        }
        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setCartProductVoList(cartProductVoList);
        cartVo.setAllChecked(this.getAllCheckedStatus(userId));
        cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

        return cartVo;
    }

    private boolean getAllCheckedStatus(Integer userId){
        if(userId == null){
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;
    }
}
